﻿/**
util.js 为中英文版本公用。
*/
var popLayer = {};
var fun;
popLayer.show = function (poptitle, popcont, popbutt, autodisappear, callback) {
    $("body").append(popLayer.create());
    if (popcont)
        $("#popcont").html(popcont);
    if (popbutt)
        $("#popsub").html(popbutt);
    if (poptitle)
        $("#popcompname").html(poptitle);
    var _l = ($(window).width() - $("#poplayer").width()) / 2 + 'px';
    var _t = $(document).scrollTop() + 150 + "px";
    $("#bgpopLayer").css("height", $(document).height());
    $("#bgpopLayer").css("width", $(document).width());
    $("#poplayer").css("left", _l);
    $("#poplayer").css("top", _t);
    //$("#poplayer-i").css("left",_l);
    //$("#poplayer-i").css("top",_t);
    if (autodisappear || autodisappear == null)
        window.setTimeout(popLayer.close, 3000);
    if (typeof (callback) == "function") {
        callback.call();
        fun = callback;
    }
}
popLayer.close = function() {
    $("#bgpopLayer").remove();
    $("#poplayer").remove();
    //$("#poplayer-i").remove();
}

popLayer.confirm = function () {
    if (typeof (fun) == "function") {
        var ck = new fun();
        ck.exe();
    }
    $("#bgpopLayer").remove();
    $("#poplayer").remove();
}


popLayer.create = function () {
    popLayer.close();
    return _layer = '\
		<div id="bgpopLayer"></div>\
		<div id="poplayer">\
			<h1>\
				\
				<p><a href="javascript:void(0)" onclick="popLayer.close()">关闭</a></p>\
			</h1>\
			<div class="pop-cont">\
				<h2 id="popcompname">' + (typeof (cms_company) != "undefined" ? cms_company.companyname : "") + '</h2>\
				<span id="popcont"></span>\
			</div>\
			<div id="popsub">\
				<input type=button onclick="popLayer.confirm()" class="submit" value="确定"/>\
			</div>\
		</div>\
	';
}


var loadingLayer = {};

loadingLayer.show = function(poptitle) {
    $("body").append(loadingLayer.create());
    var _l = ($(window).width() - $("#loadingLayer").width()) / 2 + 'px';
    var _t = $(document).scrollTop() + 150 + "px";
    $("#loadingLayerbg").css("height", $(document).height());
    $("#loadingLayerbg").css("width", $(document).width());
    $("#loadingLayer").css("left", _l);
    $("#loadingLayer").css("top", _t);
}
loadingLayer.close = function() {
    $("#loadingLayerbg").remove();
    $("#loadingLayer").remove();
    //$("#poplayer-i").remove();
}
loadingLayer.create = function() {
    loadingLayer.close();
    return _layer = '\
		<div id="loadingLayerbg"></div>\
		<div id="loadingLayer">\
			<h1>\
				\
				<p><a href="javascript:void(0)" onclick="popLayer.close()">关闭</a></p>\
			</h1>\
			<div class="pop-cont">\
				<h2 id="popcompname"></h2>\
				<span id="popcont"></span>\
			</div>\
			<div id="popsub">\
				<input type=button onclick="loadingLayer.close()" class="submit" value="确定"/>\
			</div>\
		</div>\
	';
}

function getCookie(key) {
    var _c = document.cookie;
    if (!_c.match(/uinfo=/))
        return null;
    var r = new RegExp("csinfo=[^;$]*" + key + "=([^&]+)([&]|$)");
    var arr = r.exec(_c);
    return decodeURIComponent(RegExp.$1);
}

//加载googlemap
function loadGoogleMap() {

    var _area = (typeof (cms_company) != "undefined" ? cms_company.area : (typeof (company) != "undefined" ? company.area : null));
    $.getJSON('/Scripts/home/area.txt', function(data) {
        $.each(data, function(entryIndex, entry) {
            if (entry['layrec'] == _area) {
                $("#areaName").val(entry['name']);
            }
        })
    })
        $("#map_canvas").css("display", "");
        $("#mapbody").attr("src", "/Scripts/home/googlemap.htm");
}




//文件上传
jQuery.extend({
myUpload: { u: "http://images.chinapages.com/home/upload.html",
c: "http://images.chinapages.com/home/MyCatogery.html",
d: "http://images.chinapages.com/home/deleteFile.html",
logo: "http://images.chinapages.com/home/UploadLogo.html",
v: "http://images.chinapages.com/",
im: "http://images.chinapages.com/home/UploadImage1.html",
del: "http://images.chinapages.com/home/Deleteimg.html"},
    createUploadIframe: function(id, uri) {
        //create frame
        var frameId = 'jUploadFrame' + id;

        if (window.ActiveXObject) {
            var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
            if (typeof uri == 'boolean') {
                io.src = 'javascript:false';
            }
            else if (typeof uri == 'string') {
                io.src = uri;
            }
        }
        else {
            var io = document.createElement('iframe');
            io.id = frameId;
            io.name = frameId;
        }
        io.style.position = 'absolute';
        io.style.top = '-1000px';
        io.style.left = '-1000px';

        document.body.appendChild(io);

        return io
    },
    createUploadForm: function(id, fileElementId) {
        //create form	
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id', fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        $(form).appendTo('body');
        return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()
        var form = jQuery.createUploadForm(id, s.fileElementId);
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if (s.global && !jQuery.active++) {
            jQuery.event.trigger("ajaxStart");
        }
        var requestDone = false;
        // Create the request object
        var xml = {}
        if (s.global)
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout) {
            var io = document.getElementById(frameId);
            try {
                if (io.contentWindow) {
                    xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
                    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;

                } else if (io.contentDocument) {
                    xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
                    xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
                }
            } catch (e) {
                jQuery.handleError(s, xml, null, e);
            }
            if (xml || isTimeout == "timeout") {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if (status != "error") {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType);
                        // If a local callback was specified, fire it and pass it the data
                        if (s.success)
                            s.success(data, status);

                        // Fire the global callback
                        if (s.global)
                            jQuery.event.trigger("ajaxSuccess", [xml, s]);
                    } else
                        jQuery.handleError(s, xml, status);
                } catch (e) {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete", [xml, s]);

                // Handle the global AJAX counter
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");

                // Process result
                if (s.complete)
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function() {
                    try {
                        $(io).remove();
                        $(form).remove();	

                    } catch (e) {
                        jQuery.handleError(s, xml, null, e);
                    }

                }, 100)

                xml = null

            }
        }
        // Timeout checker
        if (s.timeout > 0) {
            setTimeout(function() {
                // Check to see if the request is still happening
                if (!requestDone) uploadCallback("timeout");
            }, s.timeout);
        }
        try {
            // var io = $('#' + frameId);
            var form = $('#' + formId);
            $(form).attr('action', s.url + "?" + s.processData);
            $(form).attr('method', 'POST');
            $(form).attr('target', frameId);
            if (form.encoding) {
                form.encoding = 'multipart/form-data';
            }
            else {
                form.enctype = 'multipart/form-data';
            }
            $(form).submit();

        } catch (e) {
            jQuery.handleError(s, xml, null, e);
        }
        if (window.attachEvent) {
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else {
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }
        return { abort: function() { } };

    },

    uploadHttpData: function(r, type) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval(data);
        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            eval("data = " + data);
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();
        //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})



function changAutoTrans() {
    var autotrans = $(":input[name=autotrans]")[0].checked ? "1" : "0";
    $.post("/mypage_en/setautotrans.html?" + (new Date()).getTime(), { autotrans: autotrans }, function(dta) {
        if (dta == "1")
            alert("设置成功!");
    })
}

//弹出层上传图片 ***************************************************************************************

function GetPicList(callback) {
    var para = { userid: getCookie("uid") };

    var id = "";
    $.getJSON("/home/GetGalleryTypeList.html?" + (new Date()).getTime(), para, function(data) {

        var html = [];
        $.each(data, function(i, n) {
            html.push("<div class='topboxbut-b' name='divgetList' title='" + n.typename + "' value='" + n.id + "'>" + n.typename + "</div>");
        });
        $("#divGalleryType2").html(html.join(''));
        $("div[name=divgetList]").eq(0).removeClass("topboxbut-b").addClass("topboxbut-a");
        GetGalleryValue(callback, id);
        //点击分类触发的事件
        $("div[name=divgetList]").click(function() {

            $("div.topboxbut-a").removeClass("topboxbut-a").addClass("topboxbut-b");
            $(this).removeClass("topboxbut-b").addClass("topboxbut-a");

            id = $(this).attr("value");
            GetGalleryValue(callback, id);
        });

    });
}

function GetGalleryValue(callback, id) {
    var param = { userid: getCookie("uid"), typeid: id, pagesize: mylist_gt.pageSize, pageno: mylist_gt.currPage };

    $.getJSON("/home/GetGalleryListByType.html?" + (new Date()).getTime(), param, function(data) {
        if (mylist_gt.currPage == 1) {
            mylist_gt.total = $.grep(data, function(n, i) {

                return typeof (n.total) == "number";
            })[0].total;
            data = $.grep(data, function(n, i) {
                return typeof (n.total) == "undefined"
            });

        }
        var sp = [];
        $.each(data, function(i, n) {
            var _url = $.myUpload.v + n.imgpath + "mob_" + n.imgname;
            var s_url = $.myUpload.v + n.imgpath + "s_" + n.imgname;
            sp.push('<table border="0" style="float:left;">');
            sp.push('<tr><td><div class="bbnborder" title="' + n.title + '" name="imgdiv" value="' + _url + '"><img src="' + s_url + '" /></div></td></tr>');
            sp.push('<tr><td ><div align="center" class="TD_title" >' + n.title + '</div></td></tr>');
            sp.push('</table>');
        });

        $("#divPicList2").html(sp.join(''));
        $("#pager2").html(mylist_gt.getOutput());   //分页

        $("div[name=imgdiv]").dblclick(function() {
            var imgvalue = $(this).attr("value");
            callback(imgvalue);
        });
    });
}
//弹出图片层
var imageLayer = {};
imageLayer.show = function(callback) {
    $("body").append(imageLayer.create());

    var _l = ($(window).width() - $("#imgpoplayer").width()) / 2 + 'px';
    var _t = $(document).scrollTop() + 150 + "px";
    $("#imgbgpopLayer").css("height", $(document).height());
    $("#imgbgpopLayer").css("width", $(document).width());
    $("#imgpoplayer").css("left", _l);
    $("#imgpoplayer").css("top", _t);

    mylist_gt = new TurnPage("mylist_gt");
    mylist_gt.pageSize = 9;
    mylist_gt.callback = function() { GetPicList(callback); };
    var divGalleryType = $("#divGalleryType2").html();
    var divPicList = $("#divPicList2").html();
    GetPicList(callback);



}
imageLayer.close = function() {
    $("#imgbgpopLayer").remove();
    $("#imgpoplayer").remove();

}
imageLayer.create = function() {
    imageLayer.close();
    return _layer = '\
		<div id="imgbgpopLayer"></div>\
		<div id="imgpoplayer">\
		<h1>\
		我的图片库  (温馨提示：双击选取图片)\
				<p><a href="javascript:void(0)" onclick="imageLayer.close()">关闭</a></p>\
				</h1>\
				<div class="upfilebox" style="margin-top:10px;">\
        <table cellpadding="0" cellspacing="0" border="0">\
        <tr>\
            <td width="60" height="21" class="leftpicfor">\
                <img src="/css/mypage/images/sjt.jpg" />\
            </td>\
            <td width="360">\
                <input type="file" align="left" id="mygallerydiv" name="mygallerydiv" size="38"/>\
                <input type="button" tar="mygallerydiv" value="提交" name="upload" onclick="imageLayer.up()"/>\
            </td>\
            <input type="file" id="hiddenfile" class="hid" />\
        </tr>\
    </table>\
    <div class="textfir">\
        <span>备注：</span>格式支持jpg/jpeg ,png ,gif ,大小不超过2M。</div>\
</div>\
			<div class="pop-cont">\
			<div class="topbbn">\
			 <div  id="divGalleryType2"></div>\
            </div>\
            <div class="midbbn">\
             <div id="divPicList2"></div>\
             </div>\
			</div>\
			<div class="bombbn" >\
			<div id="pager2"></div>\
            </div>\
		</div>\
	';
}

imageLayer.up = function() {
    $.ajaxFileUpload({
        url: $.myUpload.im, secureuri: false,
        processData: 'userid=' + getCookie("uid") + '&typeId=1',
        fileElementId: 'mygallerydiv',
        dataType: 'json',
        success: function(data, status) {

            if (typeof (data) == "string" && data.match(/error=/)) {
                alert("上传的图片不符合格式或者文件过大，请检查");
                return;
            }
            alert('图片上传成功！');
            //$("#linkGallery").click();
            var urls = $.myUpload.v + data.imgpath + "mob_" + data.imgname;

            document.getElementById("edit").contentWindow.mypic(urls);
            imageLayer.close();
        },
        error: function(data) {
            alert("上传的图片不符合格式或者文件过大，请检查！");
        }
    });
}




var uploadLayer = {};

uploadLayer.show = function() {
    $("body").append(uploadLayer.create());
    var _l = ($(window).width() - $("#uploadLayer").width()) / 2 + 'px';
    var _t = $(document).scrollTop() + 150 + "px";
    $("#bgpopLayer").css("height", $(document).height());
    $("#bgpopLayer").css("width", $(document).width());
    $("#uploadLayer").css("left", _l);
    $("#uploadLayer").css("top", _t);

    var f = setInterval(function() { if ($("#pic")) clearInterval(); }, 10);
    createUpload("spanButtonPlaceholder", "progress", "btnCancel", uploadSuccess1);


}
uploadLayer.close = function() {
    $("#bgpopLayer").remove();
    $("#uploadLayer").remove();

}
uploadLayer.create = function() {
    uploadLayer.close();
    return _layer = '\
		<div id="bgpopLayer"></div>\
		<div id="uploadLayer">\
			<h1>\
				中国黄页\
				<p><a href="javascript:void(0)" onclick="uploadLayer.close()">关闭</a></p>\
			</h1>\
			<div class="pop-cont">\
				<h2 id="popcompname">已上传的文件 / 图片：</h2>\
				<span id="popcont"> \
				<p id="img">\
                      <div class="fieldset flash" id="progress" >\
                        </div>\
                        <div style="padding-left: 5px;">\
                            <span id="spanButtonPlaceholder"></span>\
                            <input id="btnCancel" type="button" value="Cancel Uploads" onclick="cancelQueue(upload2);" \
                                disabled="disabled" style="margin-left: 2px; height: 22px; font-size: 8pt;" /></div>\
                    </p>\
                    </span>\
			</div>\
		</div>\
	';
}

function openuploadlayer() {
    uploadLayer.show();

}
function GetImgs(url) {
    document.getElementById("edit").contentWindow.mypic(url);
}


